<template>
  <div class="admin-userlist-container">
    <el-main>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/manage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="search-option-userlist">
        <div class="search">
          <el-input
            class="search-input"
            placeholder="请输入用户名"
            v-model="name"
            size="medium"
          ></el-input>
          <el-button type="primary" @click="load()" size="small"
            >查询 <i class="el-icon-search"></i
          ></el-button>
          <el-button type="info" @click="reset" size="small">重置</el-button>
        </div>
        <div class="action">
          <span>批量操作：&nbsp;&nbsp;</span>
          <el-button type="success" size="mini" @click="openBanBatchDialog(0)"
            ><i class="el-icon-circle-check"></i> 解除封禁</el-button
          >
          <el-button type="danger" size="mini" @click="openBanBatchDialog(1)"
            ><i class="el-icon-circle-close"></i> 封禁</el-button
          >
          <el-button type="info" size="mini" @click="openDeleteBatchDialog()"
            ><i class="el-icon-delete"></i> 删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="userList"
        :height="600"
        border
        show-header
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          label="用户ID"
          prop="userId"
          header-align="center"
          align="center"
          sortable
          :width="90"
        >
        </el-table-column>
        <el-table-column
          label="用户名"
          header-align="center"
          align="center"
          sortable
          :width="120"
          prop="username"
        >
        </el-table-column>
        <el-table-column
          label="邮箱"
          header-align="center"
          align="center"
          prop="email"
          sortable
          :width="150"
        >
        </el-table-column>
        <el-table-column
          label="手机号"
          header-align="center"
          align="center"
          :width="150"
          sortable
          prop="phone"
        >
        </el-table-column>
        <el-table-column
          label="用户状态"
          header-align="center"
          align="center"
          :width="120"
          prop="status"
          :filters="[
            { text: '正常', value: 'ACTIVE' },
            { text: '封禁中', value: 'BANNED' },
          ]"
          :filter-method="filterStatus"
        >
          <template v-slot="{ row }">
            <el-tag
              :type="row.status === 'ACTIVE' ? 'success' : 'danger'"
              effect="plain"
            >
              {{ row.status === "ACTIVE" ? "正常" : "封禁中" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="注册时间"
          header-align="center"
          align="center"
          prop="createdAt"
          sortable
          :width="150"
        >
        </el-table-column>
        <el-table-column
          label="更新时间"
          header-align="center"
          align="center"
          :width="150"
          sortable
          prop="updatedAt"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" :width="200">
          <template v-slot="scope">
            <el-button
              v-if="scope.row.status === 'BANNED'"
              type="text"
              style="color: #67c23a"
              @click="openBanDialog(scope.row, 0)"
              size="mini"
              >解除封禁</el-button
            >
            <el-button
              v-if="scope.row.status === 'ACTIVE'"
              type="text"
              style="color: #f56c6c"
              size="mini"
              @click="openBanDialog(scope.row, 1)"
              >封禁</el-button
            >
            <el-button
              type="text"
              style="color: #00caa8"
              @click="openResetDialog(scope.row)"
              size="mini"
              >重置密码</el-button
            >
            <el-button
              type="text"
              size="mini"
              style="color: #909399"
              @click="openDeleteDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[5, 10, 20, 30]"
        layout="sizes,total, prev, pager, next"
        background
      >
      </el-pagination>
      <!-- Ban/Unban Confirm Dialog -->
      <el-dialog
        :visible="dialogVisible"
        width="300px"
        @close="dialogVisible = false"
      >
        <template slot="title">
          <span> <i class="el-icon-warning-outline"></i>&nbsp;提示</span>
        </template>
        <span style="font-size: 14px">
          确定要{{ banAction === 1 ? "封禁" : "解除封禁" }}用户
          <b>{{ currentUsername }}</b>
          吗？
        </span>
        <template slot="footer">
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="confirmBan" size="mini"
            >确定</el-button
          >
        </template>
      </el-dialog>
      <el-dialog
        :visible="dialogVisibleDelete"
        width="300px"
        @close="dialogVisibleDelete = false"
      >
        <template slot="title">
          <span> <i class="el-icon-warning-outline"></i>&nbsp;提示</span>
        </template>
        <span style="font-size: 14px">
          确定要删除用户
          <b>{{ currentUsername }}</b>
          吗？
        </span>
        <template slot="footer">
          <el-button @click="dialogVisibleDelete = false" size="mini"
            >取消</el-button
          >
          <el-button type="primary" @click="confirmDelete" size="mini"
            >确定</el-button
          >
        </template>
      </el-dialog>
      <el-dialog
        title="重置用户密码"
        :visible.sync="dialogVisibleReset"
        class="address-dialog"
        width="500px"
        @close="dialogVisibleReset = false"
      >
        <el-form
          class="form"
          :model="dialogForm"
          :rules="dialogRules"
          ref="dialogFormRef"
          label-width="auto"
        >
          <el-form-item prop="newPassword" label="新密码">
            <el-input
              type="password"
              v-model="dialogForm.newPassword"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword" label="确认密码">
            <el-input
              type="password"
              v-model="dialogForm.confirmPassword"
              placeholder="请确认密码"
              show-password
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleReset = false" size="mini"
            >取 消</el-button
          >
          <el-button type="primary" @click="editPassword" size="mini"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-main>
  </div>
</template>

<style lang="scss">
.admin-userlist-container {
  min-height: 800px;
  background-color: #fff;
  border-radius: 20px;
  padding: 20px;
  .search-option-userlist {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    .search {
      .search-input {
        width: 250px;
        display: inline-block;
        margin-right: 10px;
      }
    }
    .action {
      span {
        font-size: 12px;
      }
      .el-button {
        // margin: 0 10px;
        border-radius: 5px;
      }
    }
  }
}
</style>

<script>
export default {
  data() {
    let password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error("密码的长度必须为6~20位"));
      } else {
        callback();
      }
    };
    let confirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请确认密码"));
      } else if (value !== this.dialogForm.newPassword) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      userList: [],
      page: 1,
      pageSize: 10,
      name: "",
      dialogVisible: false,
      dialogVisibleDelete: false,
      dialogVisibleReset: false,
      currentUser: null,
      currentUsername: "",
      batchBan: 0,
      batchDelete: 0,
      deleteBatch: 0,
      banAction: 1, // 1: ban, 0: unban
      multipleSelection: [],
      dialogForm: {
        newPassword: "",
        confirmPassword: "",
      },
      dialogRules: {
        newPassword: [{ validator: password, trigger: "blur", required: true }],
        confirmPassword: [
          { validator: confirmPassword, trigger: "blur", required: true },
        ],
      },
    };
  },
  created() {
    this.load();
  },
  mounted() {},
  methods: {
    handleCurrentChange(page) {
      this.page = page;
      this.load();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    load() {
      this.$axios
        .get(
          `/admin/user/${this.page}/${this.pageSize}?username=${this.name}&userType=NORMAL`
        )
        .then(
          (res) => {
            if (res && res.status === 200) {
              this.userList = res.data.data.records;
              this.total = res.data.data.total;
            } else {
              this.$message.error(res.data.data);
            }
          },
          (err) => {
            this.$message.error(err || "获取用户信息失败");
          }
        );
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    filterStatus(value, row) {
      return row.status === value;
    },
    reset() {
      this.page = 1;
      this.pageSize = 10;
      this.name = "";
      this.load();
    },
    openBanDialog(user, action) {
      this.batchBan = 0;
      this.currentUser = user;
      this.currentUsername = user.username;
      this.banAction = action;
      this.dialogVisible = true;
    },
    openBanBatchDialog(action) {
      // console.log(this.multipleSelection);
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择用户");
        return;
      }
      this.batchBan = 1;
      this.currentUsername = this.multipleSelection
        .map((item) => item.username)
        .join(", ");
      this.banAction = action;
      this.dialogVisible = true;
    },
    confirmBan() {
      if (!this.batchBan) {
        this.handleBan();
      } else {
        this.handleBanBatch();
      }
      this.dialogVisible = false;
    },
    handleBanBatch() {
      if (this.banAction) {
        this.$axios
          .post(
            "/admin/user/batch/ban",
            this.multipleSelection.map((item) => item.userId)
          )
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success("封禁用户成功！");
              this.load();
            } else {
              this.$message.error(res.data.data);
            }
          });
      } else {
        this.$axios
          .post(
            "/admin/user/batch/unban",
            this.multipleSelection.map((item) => item.userId)
          )
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success("解除封禁用户成功！");
              this.load();
            } else {
              this.$message.error(res.data.data);
            }
          });
      }
      this.dialogVisible = false;
    },
    handleBan() {
      // action: 1=ban, 0=unban
      if (this.banAction) {
        this.$axios
          .post(`/admin/user/ban/${this.currentUser.userId}`)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success("封禁用户成功！");
              this.load();
            } else {
              this.$message.error(res.data.data);
            }
          });
      } else {
        this.$axios
          .post(`/admin/user/unban/${this.currentUser.userId}`)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success("解除封禁用户成功！");
              this.load();
            } else {
              this.$message.error(res.data.data);
            }
          });
      }
    },
    openDeleteDialog(user) {
      this.batchDelete = 0;
      this.currentUser = user;
      this.currentUsername = user.username;
      this.dialogVisibleDelete = true;
    },
    openDeleteBatchDialog() {
      // console.log(this.multipleSelection);
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择用户");
        return;
      }
      this.batchDelete = 1;
      this.currentUsername = this.multipleSelection
        .map((item) => item.username)
        .join(", ");
      this.dialogVisibleDelete = true;
    },
    confirmDelete() {
      if (!this.batchDelete) {
        this.handleDelete();
      } else {
        this.handleDeleteBatch();
      }
      this.dialogVisibleDelete = false;
    },
    handleDelete() {
      this.$axios
        .delete(`/admin/user/remove/${this.currentUser.userId}`)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除用户成功！");
            this.load();
          } else {
            this.$message.error(res.data.data);
          }
        });
    },
    handleDeleteBatch() {
      this.$axios
        .delete("/admin/user/batchRemove", {
          data: this.multipleSelection.map((item) => item.userId),
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除用户成功！");
            this.load();
          } else {
            this.$message.error(res.data.data);
          }
        });

      this.dialogVisible = false;
    },
    openResetDialog(user) {
      this.currentUser = user;
      this.dialogVisibleReset = true;
    },
    editPassword() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {
          this.$axios
            .post("/admin/user/resetPwd", {
              newPassword: this.dialogForm.newPassword,
              userId: this.currentUser.userId,
            })
            .then((response) => {
              if (response.data.code === 200) {
                this.dialogVisibleReset = false;
                this.$message.success("重置用户密码成功！");
              } else {
                this.$message.error(response.data.message);
              }
            });
        }
      });
    },
  },
};
</script>